from rest_framework.views import APIView
from rest_framework.response import Response
from .sers import *
import jwt
from h2004a_md.settings import SECRET_KEY
from goodsapp.models import Goods

from rest_framework.authentication import BaseAuthentication
import redis

r = redis.Redis(decode_responses=True)


# 自定义我们自己的 令牌认证类
class MyTokenAuth(BaseAuthentication):
    def authenticate(self, request):
        try:
            # 解析令牌
            token = request.GET.get("token")
            uid = jwt.decode(token, SECRET_KEY)["uid"]
            user = UserProfile.objects.get(id=uid)
            # 返回 是一个元组 第一个是 用户对象 第二个是 令牌
            return (user, token)
        except Exception as e:
            print(e)
            return (None, None)


# 根据用户id 查找用户的详细信息

class UserDetailView(APIView):
    authentication_classes = [MyTokenAuth]

    def get(self, request):
        user = request.user

        print("user:", user)

        user = UserProfile.objects.get(id=user.id)

        # 获取到用户的浏览记录
        queryset_history = GoodsHistory.objects.filter(user_id=user.id)

        resp = {
            "info": UserDetailSer(user).data,
            "history_list": GoodsHistoryListSer(queryset_history, many=True).data
        }

        return Response(resp)

    def put(self, request):
        user = request.user
        # 1、更新 用户的信息，:邮箱、密码
        email = request.data.get("email")
        user.email = email
        # 修改
        user.save()

        return Response({"msg": "绑定邮箱"})


class UserPasswordView(APIView):
    authentication_classes = [MyTokenAuth]

    def post(self, request):
        user = request.user
        print(user)
        password = request.data.get("password")
        new_password = request.data.get("password1")

        if user.check_password(password):
            # 修改密码
            #  Django 的 User 设置密码 使用set_password  内部会加密密码的
            user.set_password(new_password)
            return Response({"msg": "密码修改成功", "code": 200})
        else:

            return Response({"msg": "当前密码不正确", "code": 400})


# 定义 省市县的 接口

class CityView(APIView):

    def get(self, request):
        pid = request.GET.get("pid")
        queryset = City.objects.filter(parentid=pid)

        ser = CitySer(queryset, many=True)

        return Response(ser.data)


# 地址接口 实现 查询、添加

class AddressView(APIView):
    authentication_classes = [MyTokenAuth]

    def post(self, request):
        request.data["user"] = request.user.id
        ser = AddressSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({"msg": "添加成功", "code": 200})
        else:
            print(ser.errors)
            return Response({"msg": "添加失败", "code": 400})

    def get(self, request):
        # 获取 用户的所有地址
        queryset = Address.objects.filter(user_id=request.user.id)
        ser = AddressListSer(queryset, many=True)
        return Response(ser.data)


# 开发一个商品浏览接口

class GoodsHistoryView(APIView):
    authentication_classes = [MyTokenAuth]

    def get(self, request):
        user = request.user

        queryset = GoodsHistory.objects.filter(user_id=user.id)
        ser = GoodsHistoryListSer(queryset, many=True)

        return Response(ser.data)

    def post(self, request):
        user = request.user
        gid = request.data.get("gid")
        GoodsHistory.objects.create(user_id=user.id, goods_id=gid)

        return Response({"msg": "添加成功"})


class CollectView(APIView):
    authentication_classes = [MyTokenAuth]

    def get(self, request):
        #  获取到该用户下的所有收藏
        user = request.user

        gid_set = r.smembers("collect_" + str(user.id))  # 获取一个集合
        print(gid_set)
        # 根据商品的id去 查找 所有的商品
        queryset = Goods.objects.filter(id__in=gid_set)
        ser = GoodsListSer(queryset, many=True)
        return Response(ser.data)

    def post(self, request):
        #
        user = request.user
        # 获取要收藏的商品
        gid = request.data.get("gid")

        # 把 redis 存储到
        r.sadd("collect_" + str(user.id), gid)

        return Response({"msg": "收藏成功", "code": 200})
